<template>
  <div>
    <el-card class="register-card">
      <h2 class="register-title">用户注册</h2>
      <el-form :model="registerForm" ref="registerFormRef" :rules="rules" label-width="100px">
        <el-form-item label="用户名(学号)" prop="username">
          <el-input v-model="registerForm.username" placeholder="请输入学号"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="registerForm.password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input type="password" v-model="registerForm.confirmPassword" placeholder="请确认密码"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="registerForm.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="registerForm.gender">
            <el-radio label="male">男</el-radio>
            <el-radio label="female">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="学院" prop="college_id">
          <el-select v-model="registerForm.college_id" placeholder="请选择学院">
            <el-option v-for="college in colleges" :key="college.id" :label="college.name" :value="college.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-select v-model="registerForm.grade" placeholder="请选择年级">
            <el-option v-for="year in years" :key="year" :label="`${year}年入学`" :value="year"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级名称" prop="class_name">
          <el-select v-model="registerForm.class_name" placeholder="请选择班级">
            <el-option v-for="classItem in classList" :key="classItem.id" :label="classItem.name" :value="classItem.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电话" prop="tel_number">
          <el-input v-model="registerForm.tel_number" placeholder="请输入电话"></el-input>
        </el-form-item>
        <el-form-item label="QQ" prop="qq_number">
          <el-input v-model="registerForm.qq_number" placeholder="请输入QQ"></el-input>
        </el-form-item>
        <el-form-item label="是否是班委" prop="is_class_committee">
          <el-select v-model="registerForm.is_class_committee" placeholder="请选择">
            <el-option label="是" :value="true"></el-option>
            <el-option label="否" :value="false"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="registerForm.is_class_committee" label="班委类型" prop="class_committee_type">
          <el-select v-model="registerForm.class_committee_type" placeholder="请选择班委类型">
            <el-option label="班长" value="monitor"></el-option>
            <el-option label="学习委员" value="study_committee"></el-option>
            <el-option label="体育委员" value="sports_committee"></el-option>
            <el-option label="其他班委" value="others_committee"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleRegister">注册</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted, watch, computed } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { fetchColleges, fetchClasses, registerUser } from "@/api/api";

export default {
  name: "UserRegister",
  setup() {
    const registerForm = ref({
      username: "",
      password: "",
      confirmPassword: "",
      name: "",
      gender: "",
      grade: "",
      college_id: null,
      class_name: "",
      tel_number: "",
      qq_number: "",
      is_class_committee: false,
      class_committee_type: null,
    });

    const registerFormRef = ref(null);
    const router = useRouter();
    const colleges = ref([]);
    const classList = ref([]);
    

    const years = computed(() => {
      const currentYear = new Date().getFullYear();
      return Array.from(
        { length: currentYear - 1900 },
        (_, i) => currentYear - i
      );
    });

    const fetchCollegesData = async () => {
      try {
        const data = await fetchColleges();
        colleges.value = data;
      } catch (error) {
        ElMessage.error(error.message);
      }
    };

    const fetchClassesData = async () => {
      if (!registerForm.value.grade || !registerForm.value.college_id) {
        ElMessage.warning("请选择年级和学院");
        classList.value = [];
        registerForm.value.class_name = "";
        return;
      }
      try {
        const data = await fetchClasses(
          registerForm.value.grade,
          registerForm.value.college_id
        );
        classList.value = data;
        sortResults(); // 获取数据后立即排序
      } catch (error) {
        ElMessage.error(error.message);
        classList.value = [];
        registerForm.value.class_name = "";
      }
    };

    const handleRegister = async () => {
      registerForm.value.com_member_type = registerForm.value.is_class_committee
        ? 1
        : 0;
      registerFormRef.value.validate(async (valid) => {
        if (valid) {
          registerForm.value.grade = parseInt(registerForm.value.grade, 10);

          try {
            await registerUser({
              username: registerForm.value.username,
              password: registerForm.value.password,
              name: registerForm.value.name,
              gender: registerForm.value.gender === "male",
              college_id: registerForm.value.college_id,
              class_id: registerForm.value.class_name,
              tel_number: registerForm.value.tel_number,
              qq_number: registerForm.value.qq_number || "",
              com_member_type: registerForm.value.com_member_type,
              grade: registerForm.value.grade,
            });
            ElMessage.success("注册成功！");
            router.push("/UserLogin");
          } catch (error) {
            ElMessage.error(error.message);
          }
        } else {
          ElMessage.error("请填写完整信息");
        }
      });
    };

    const sortResults = () => {
  classList.value.sort(((a, b) => {
    const extractNumber = (str) => {
      const match = str.match(/(\d+)/);
      return match ? parseInt(match, 10) : Number(str);
    };
    const numA = extractNumber(a.name);
    const numB = extractNumber(b.name);
    const textA = a.name.replace(/\d+/g, '');
    const textB = b.name.replace(/\d+/g, '');
    if (textA.localeCompare(textB) !== 0) {
      return textA.localeCompare(textB);
    }
    return numA - numB;
  }));
};

    onMounted(() => {
      fetchCollegesData(); // 钩子获取学院列表
    });
    watch(
      () => [registerForm.value.grade, registerForm.value.college_id],
      () => {
        registerForm.value.class_name = ""; // 重置班级选择
        fetchClassesData();
      },
      { immediate: true }
    );

    return {
      registerForm,
      registerFormRef,
      colleges,
      classList,
      handleRegister,
      years,
      sortResults,
    };
  },
};
</script>

<style scoped>
.register-card {
  width: 400px;
  margin: 100px auto;
  padding: 20px;
}

.register-title {
  text-align: center;
  margin-bottom: 20px;
}
</style>